/*
    规范接口为 LOG(lever,"xxxx",...)
*/
#ifndef __LOG_H__
#define __LOG_H__
#include <sys/time.h>
#include <stdio.h>
#include <time.h>
#include <syslog.h>

#define LOG_USE_STATIC_CONF_SIMPLE              /* 不使用外置库比如zlog,单文件即可使用*/

#ifdef  LOG_USE_STATIC_CONF_SIMPLE
#define LOG_LEV             DEBUG               /*数字越低,输出信息越多*/
#define LOG_USE_CONSOLE     stdout
#define LOG_USE_FILE        "dc.log"      /* __FILE__".log" */
#define LOG_SYS_USE         1                   /*1打开 0关闭  /var/log/xxx */
#endif

typedef enum {
	DEBUG = 0,
	INFO = 1,
	NOTICE = 2,
	WARN = 3,
	ERROR = 4,
	FATAL = 5
} log_level;
static const char *log_msg[10]={"DEBUG","INFO","NOTICE","WARN","ERROR","FATAL"};
static int syslog_id[]={LOG_DEBUG,LOG_INFO,LOG_NOTICE,LOG_WARNING,LOG_ERR,LOG_EMERG};
static FILE *g_log_fp;
static int syslog_flag=0;

#ifndef LOG_SYS_USE
#define LOG_SYS_USE 0
#endif
#ifndef LOG_USE_CONSOLE
#define LOG_USE_CONSOLE 0
#endif


#ifdef  LOG_USE_STATIC_CONF_SIMPLE
#define LOG_MESSAGE_RAW(level, fmt, para...)    do \
    { \
        time_t t = time(NULL);  \
        struct tm *tmm = localtime(&t); \
        if(level>=LOG_LEV)     \
            if(g_log_fp>0)fprintf(g_log_fp,  "[%s-%d-%02d-%02d %02d:%02d:%02d][%s][%s:%d]" fmt "\n",log_msg[level],tmm->tm_year+1900,tmm->tm_mon+1,tmm->tm_mday,tmm->tm_hour,tmm->tm_min,tmm->tm_sec,__FUNCTION__,__FILE__,__LINE__,##para); \
            fflush(g_log_fp);\
            if(LOG_USE_CONSOLE)fprintf(LOG_USE_CONSOLE,  "[%s-%d-%02d-%02d %02d:%02d:%02d][%s][%s:%d]" fmt "\n",log_msg[level],tmm->tm_year+1900,tmm->tm_mon+1,tmm->tm_mday,tmm->tm_hour,tmm->tm_min,tmm->tm_sec,__FUNCTION__,__FILE__,__LINE__,##para); \
            if(LOG_SYS_USE)syslog(syslog_id[level],"[%s]-" fmt,log_msg[level],##para);\
    } while(0)

#define LOG  LOG_MESSAGE_RAW
#else
// use zlog
#define LOG(level, fmt, para...) do \
    { \
        fprintf(stdout,  "[%s-][%s][%s:%d]" fmt "\n",log_msg[level],__FUNCTION__,__FILE__,__LINE__,##para); \
    } while(0)
#endif

static int LOGInit()
{
    #ifdef LOG_USE_FILE
    g_log_fp = fopen(LOG_USE_FILE,"a+");
    if (g_log_fp == NULL)
    {
        perror("open log file error\n");
         g_log_fp=stderr;
    } 
    #else
    g_log_fp=0;
    #endif
}

// #include <unistd.h>
// void TestLog()
// {
//     LOGInit();
//     while(1)
//     {
//         LOG_MESSAGE_RAW(DEBUG,"hello%s","123");
//         LOG_MESSAGE_RAW(DEBUG,"hello 222");
//         sleep(2);
//     }

// }


// int main()
// {
//     TestLog();
//     return 0;
// }
#endif